import json
import os.path
import re
import time

from bs4 import BeautifulSoup
import requests

url = 'https://www.kugou.com/yy/rank/home/1-6666.html?from=homepage'
headers = {
    'Cookie': 'kg_mid=e071c1d3970aec5fa870005566887f90; kg_dfid=2UIw8X1SPjbm1JMdeB1oS5rW; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1642664446,1642685413; kg_mid_temp=e071c1d3970aec5fa870005566887f90; Hm_lpvt_aedee6983d4cfc62f509129360d6bb3d=1642691141',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36'
           }
req = requests.get(url, headers=headers)
# soup = BeautifulSoup(req.text, 'lxml')
# song_name = soup.select('.pc_temp_songname')
re_hash = re.compile('"Hash":"(.*?)"', re.S | re.I)
re_album = re.compile('"album_id":(\d+)', re.S | re.I)
re_song_url = re.compile('"play_url":"(.*?)"', re.S | re.I)
re_song_name = re.compile('"song_name":"(.*?)"', re.S | re.I)
hashs = re_hash.findall(req.text)
album_dis = re_album.findall(req.text)

if not os.path.exists('resource'):
    os.makedirs('resource')

detail_url = 'https://wwwapi.kugou.com/yy/index.php?'

for hash_, album_ in zip(hashs, album_dis):
    params = {
        'r': 'play/getdata',
        'callback': 'jQuery19101644300590846064_1642691141378',
        'hash': hash_,
        'dfid': '2UIw8X1SPjbm1JMdeB1oS5rW',
        'appid': '1014',
        'mid': 'e071c1d3970aec5fa870005566887f90',
        'platid': '4',
        'album_id': album_,
        '_': '1642691141380'
    }
    song_html = requests.get(detail_url, params=params, headers=headers)
    # 正则表达式取json
    # song_url = re_song_url.findall(song.text)[0].replace('\\', '')
    # song_name = re_song_name.findall(song.text)[0]

    # json解析取信息 优点：不用进行转码
    start_pos = song_html.text.find('{"status"')
    end_pos = song_html.text.find(');')
    song_data = json.loads(song_html.text[start_pos:end_pos])
    song_url = song_data['data']['play_url']
    song_name = song_data['data']['song_name']
    print(song_url, song_name)
    # 如果使用正则表达式进行解析提取，则需要进行转码
    # song_name = song_name.encode('utf-8').decode('unicode_escape')
    print(f'正在下载:{song_name}')
    try:
        with open(f'./resource/{song_name}.mp3', 'wb') as f:
            f.write(requests.get(song_url).content)
    except Exception:
        print('下载出错！')
    time.sleep(1)



